﻿module Sustainalytics.Routing {

    import Claims = Sustainalytics.Claims;
    import Authentication = Sustainalytics.Authentication;

    export class RoutingServiceProvider extends RoutingServiceProviderBase implements IRoutingServiceProvider, ng.IServiceProvider {

        constructor(
            private $routeProvider: ng.route.IRouteProvider) {

            super();

            var ctx = this;

            (<any>ctx).$get = ['$rootScope', '$q', 'ClaimsAuthorizationService', '$injector', '$route', '$routeParams', function ($rootScope, $q, ClaimsAuthorizationService, $injector, $route, $routeParams) {

                // crate routing engine adapter
                var routingEngineAdapter = new RoutingEngineAdapter($route, $routeParams);

                return new RoutingService($rootScope, $q, ClaimsAuthorizationService, $injector, ctx.routeInfoMap, routingEngineAdapter);
            }];
        }

        public $get: any;


        // what to do when path is reached
        public when(path: string, route: ng.route.IRoute, security?: RouteSecurity, requires?: string[]): IRoutingServiceProvider {
            var ctx = this;

            ctx.routeInfoMap.addRouteInfo(
                {
                    path: path,
                    security: security
                });

            ctx.applyRouteResolver(route, security, path, requires);

            // add route
            ctx.$routeProvider.when(path, route);

            return ctx;
        }

        // what to do if no when is met
        public otherwise(route: ng.route.IRoute, security?: RouteSecurity, requires?: string[]): IRoutingServiceProvider {
            var ctx = this;

            ctx.applyRouteResolver(route, security, null, requires);

            ctx.$routeProvider.otherwise(route);

            return ctx;
        }


        // apply security to route by injecting additional services into route.resolve property
        private applyRouteResolver(route: ng.route.IRoute, security: RouteSecurity, path: string, requires: string[]): void {
            var ctx = this;

            var authViaResolve =
                {
                    refreshTokenChecker: super.createRouteResolver(security, path, requires)
                };

            // extend resolve to include route security checking
            route.resolve = $.extend(route.resolve, authViaResolve, true);
        }
    }

    //angular.module(routingModuleName).provider(routingServiceName,
    //    ['$routeProvider', RoutingServiceProvider]);
} 